import { Component, OnInit, ViewEncapsulation, ViewChild, AfterViewInit, NgZone } from '@angular/core';
import { DxTreeListComponent } from 'devextreme-angular';

@Component({
  selector: 'app-tree-list',
  templateUrl: './index.html',
  styleUrls: ['./index.scss'],
  encapsulation: ViewEncapsulation.None
})
export class TreeListDemoComponent implements OnInit, AfterViewInit {

  @ViewChild('tree')
  tree: DxTreeListComponent;
  treeListColumns: any[];
  dataSources = [];


  employees = [
    {
      id: '1',
      fullName: 'John Heart',
      position: 'CEO',
      date: new Date(),
      childs: [{
        id: '1_1',
        fullName: 'Samantha Bright',
        position: 'COO'
      }]
    },
    {
      id: '2',
      fullName: 'Robert Reagan',
      position: 'CMO',
      childs: [{
        id: '2_1',
        fullName: 'Greta Sims',
        position: 'HR Manager'
      }]
    },
  ];

  categories: any[] =
    [{
      id: 'c1',
      isCategory: true,
      fullName: 'Category 1',
      childs: [this.employees[0]]
    }, {
      id: 'c2',
      isCategory: true,
      fullName: 'Category 2',
      childs: [this.employees[1]]
    }];

  constructor(private _zone: NgZone) {
    this.dataSources = [].concat(...this.categories);
    console.log(this.dataSources);
  }

  ngOnInit(): void {
    this.treeListColumns = Object.keys(COLUMNS_CONFIG).map(k => {
      const r = {
        dataField: k,
        caption: COLUMNS_CONFIG[k]
      };
      return r;
    });
  }

  ngAfterViewInit(): void {
    this._zone.runOutsideAngular(() => {
      this.tree.onRowPrepared.subscribe(this.onRowPrepared.bind(this));
    });
  }

  public onRowPrepared(e: any) {
    if (e.rowType !== 'data') {
      return;
    }

    const rowEle = e.rowElement as HTMLElement;
    const rowClass = this._getRowClassDynamic(e.data);
    if (!!rowClass) {
      rowEle.classList.add(rowClass);
    }

    if (!!e.data.isCategory) {
      this._dealCategoryRow(rowEle);
    }

    console.log('------tree rows', e, rowClass);
  }

  private _dealCategoryRow(rowEle: HTMLElement) {
    const cells = Array.from(rowEle.querySelectorAll('td')) as HTMLElement[];
    const totalCols = cells.reduce((pre, cur) => {
      const col = cur.getAttribute('colspan') || '1';
      return pre + (+col);
    }, 0);
    cells[0].setAttribute('colspan', totalCols.toString());

    cells.forEach((cell, index) => {
      if (index !== 0) {
        cell.style.width = '0px';
      }
    });
  }

  private _getRowClassDynamic(data: any) {
    return data.isCategory ? 'category-row' + data.id : 'data-row';
  }
}



export const COLUMNS_CONFIG = {
  'id': '标识',
  'fullName': '全名',
  'position': '职位',
  'date': '日期'
};

